package com.swlz.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.swlz.Const;
import com.swlz.service.ConfigService;
import com.swlz.service.impl.ConfigServiceImpl;
import com.swlz.vo.LoginUser;

/**
 * <pre>
 * - 权限过滤器
 * ClassName : com.swlz.filter.AuthFilter
 * Author : swlz
 * E-Mail : 2233875735@qq.com
 * Date : 2020-8-6 15:52:01
 * Version : 1.0
 * Copyright 2020 swlz.top Inc. All rights reserved. 
 * Warning: this content is only for internal circulation of the company. It is forbidden to divulge it or use it for other commercial purposes
 * </pre>
 *
 */
@WebFilter("/*")
public class AuthFilter implements Filter {
	private ConfigService service = new ConfigServiceImpl();
	
	/**
	 * - 需要进行权限判断的路径
	 */
	public List<String> authList = new ArrayList<String>();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		java.util.Collections.addAll(authList, "user","admin","author");
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		
	
		
		
		String path = req.getRequestURI();
		path = path.substring(req.getContextPath().length()+1);
		
		int index = path.indexOf("/");
		if(index==-1) {
			chain.doFilter(request, response);
		}else {
			path = path.substring(0,index);
			if(authList.contains(path)) {
				LoginUser user = Const.getLoginUser(req.getSession());
				if(user==null) {
					res.sendRedirect(req.getContextPath()+"/login1.jsp");//如果没有登录，。。
				}else {
					if(user.getRoleCode().equals("admin")) {//管理员什么都可以做
						chain.doFilter(request, response);
					}else if(user.getRoleCode().equals("author")&&path.equals("author")) {//特定的角色只能进入特定的目录
						chain.doFilter(request, response);
					}else if(path.equals("user")) {//用户目录只要登录的用户就可以访问
						chain.doFilter(request, response);
					}else {
						res.sendError(403, "您无权访问");
					}
				}
			}else {
				chain.doFilter(request, response);
			}
		}
		
		
		
		
		
	}

	@Override
	public void destroy() {}

}